<template>
  <div class="car-page-wrapper">
    <div class="header">
      <div class="search">
        <a-input
          :style="{ width: '320px' }"
          placeholder="按下Enter进行搜索"
          allow-clear
          @change="handleSearch"
        />
        <a-button type="primary" @click="handleSearch">搜索</a-button>
      </div>

      <template v-if="userInfo?.role === 2">
        <div class="operations">
          <a-button @click="() => setModalVisible(true)">添加商品</a-button>
        </div>
      </template>
    </div>

    <div class="body">
      <template v-for="item in filteredData" :key="item.id">
        <carCard :data="item">
          <template v-if="userInfo?.role === 2" #default>
            <a-button @click="handleDelete({ id: item.id })" type="danger">
              删除
            </a-button>
          </template>
          <template v-if="userInfo?.role === 1" #default>
            <div class="buttons">
              <a-button @click="addToShoppingCart(item)" type="danger">
                加入购物车
              </a-button>
              <a-button @click="handleAppoint(item.id)" type="danger">
                预约看车
              </a-button>
            </div>
          </template>
        </carCard>
      </template>
    </div>

    <modal :setVisible="setModalVisible" :visible="modalVisible">
      <a-form :model="form" @submit="handleSubmit">
        <a-form-item field="filename" tooltip="请上传文件" label="封面图">
          <a-upload
            v-model="form.file"
            :on-before-upload="handlePictureUpload"
          />
        </a-form-item>

        <a-form-item field="model" label="模型">
          <a-input v-model="form.model" placeholder="请输入模型" />
        </a-form-item>

        <a-form-item field="bodytype" label="车型">
          <a-input v-model="form.bodytype" placeholder="请输入车型" />
        </a-form-item>

        <a-form-item field="fueltype" label="燃料类型">
          <a-input v-model="form.fueltype" placeholder="请输入燃料类型" />
        </a-form-item>

        <a-form-item field="mileage" label="里程">
          <a-input v-model="form.mileage" placeholder="请输入里程" />
        </a-form-item>

        <!-- 外饰颜色 -->
        <a-form-item field="exteriorcolor" label="外饰颜色">
          <a-input v-model="form.exteriorcolor" placeholder="请输入外饰颜色" />
        </a-form-item>

        <!-- 内饰颜色 -->
        <a-form-item field="interiorcolor" label="内饰颜色">
          <a-input v-model="form.interiorcolor" placeholder="请输入内饰颜色" />
        </a-form-item>

        <a-form-item field="price" label="价格">
          <a-input v-model="form.price" placeholder="请输入价格" />
        </a-form-item>

        <a-form-item field="discount" label="优惠">
          <a-input v-model="form.discount" placeholder="请输入价格" />
        </a-form-item>

        <a-form-item field="description" label="描述">
          <a-input v-model="form.description" placeholder="请输入描述" />
        </a-form-item>

        <a-form-item field="stock" label="库存">
          <a-input v-model="form.stock" placeholder="请输入库存" />
        </a-form-item>

        <a-form-item field="type" label="是否为新车">
          <a-radio-group v-model="form.isnew">
            <a-radio value="1">是</a-radio>
            <a-radio value="0">否</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item field="type" label="类型">
          <a-radio-group v-model="form.type">
            <a-radio value="0">状态0</a-radio>
            <a-radio value="1">状态1</a-radio>
            <a-radio value="2">妆台2</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item>
          <a-button html-type="submit">提交</a-button>
        </a-form-item>
      </a-form>
    </modal>

    <modal
      :set-visible="setAppointmentModalVisible"
      :visible="appointmentModalVisible"
      title="预约时间"
    >
      <div class="time-wrapper">
        <a-range-picker
          showTime
          :defaultValue="[]"
          value-format="Date"
          @change="handleTimeChange"
        />
        <a-button @click="commitAppoint" type="primary">确定</a-button>
      </div>
    </modal>
  </div>
</template>

<script setup lang="ts">
import carCard from "@/components/car/car-card/index.vue";
import { commonRequest } from "@/utils/request";
import { onMounted } from "vue";
import modal from "@/components/common/modal/index.vue";
import { ref } from "vue";
import { reactive } from "vue";
import { Message } from "@arco-design/web-vue";
import axios from "axios";

const baseForm = {
  file: "",
  model: "",
  bodytype: "",
  fueltype: "",
  mileage: "",
  exteriorcolor: "",
  interiorcolor: "",
  price: "",
  discount: "",
  description: "",
  stock: "",
  isnew: "1",
  type: "0",
};

const allData = ref(null);
const filteredData = ref([]);

const modalVisible = ref(false);
const form = reactive(baseForm);
const userInfo = ref(null);
const appointmentModalVisible = ref(false);
const appointmentTimeRange = ref([]);
const appointmentCardId = ref(null);

const handlePictureUpload = (data) => {
  console.log(data);
  form.file = data;
};

const handleTimeChange = (v) => {
  console.log(v);
  appointmentTimeRange.value = v;
};

const commitAppoint = async () => {
  const data = {
    appointmenttime: appointmentTimeRange.value[0],
    fulltime: appointmentTimeRange.value[1],
    userid: `${userInfo.value.id}`,
    carid: `${appointmentCardId.value}`,
  };
  console.log(data);
  const res = await commonRequest.post("/appointmentviewing/add", data);
  if (res.data.code === 200) {
    Message.success("预约成功");
    setAppointmentModalVisible(false);
  } else {
    Message.error("预约失败");
  }
};

const handleAppoint = async (id) => {
  appointmentCardId.value = id;
  setAppointmentModalVisible(true);
};

const getCars = async () => {
  const data =
    userInfo.value?.role === 2
      ? {
          businessid: userInfo.value.id,
        }
      : {};

  const res = await commonRequest.post("/carproducts/select", data);
  allData.value = res.data?.date ?? [];
  filteredData.value = allData.value;
};

const setModalVisible = (v: boolean) => {
  modalVisible.value = v;
};

const setAppointmentModalVisible = (v: boolean) => {
  appointmentModalVisible.value = v;
};

const handleDelete = async (data: any) => {
  const res = await commonRequest.post("/carproducts/delete", `${data.id}`);
  if (res.data.code === 200) {
    Message.success("删除成功");
    getCars();
  }
};

const sendFormData = async () => {
  const userInfoJSON = localStorage.getItem("userInfo");
  const token = localStorage.getItem("jwtToken");
  const userInfo = JSON.parse(userInfoJSON);

  const formData = new FormData();

  formData.append("file", form.file); // 文件
  formData.append("model", form.model);
  formData.append("bodytype", form.bodytype);
  formData.append("fueltype", form.fueltype);
  formData.append("mileage", form.mileage);
  formData.append("exteriorcolor", form.exteriorcolor);
  formData.append("interiorcolor", form.interiorcolor);
  formData.append("price", form.price);
  formData.append("discount", form.discount);
  formData.append("description", form.description);
  formData.append("stock", form.stock);
  formData.append("isnew", form.isnew); // 注意转换为字符串
  formData.append("businessid", `${userInfo.id}`);

  const config = {
    headers: {
      Authorization: `${token}`, // 假设token前需要'Bearer '，根据实际情况调整
      "Content-Type": "multipart/form-data", // 让axios自动设置Content-Type为multipart/form-data
    },
  };

  const res = await axios.post(
    `${import.meta.env.VITE_APP_COMMON_API_BASE_URL}/shale/carproducts/add`,
    formData,
    config
  );
  if (res.data.code === 200) {
    Message.success("添加成功");
  }
};

const handleSubmit = async () => {
  await sendFormData();
  setModalVisible(false);
  getCars();
};

const handleSearch = (value: string) => {
  console.log(value);
  if (value) {
    const v = value.toLowerCase();
    filteredData.value = allData.value.filter((item: any) => {
      return (
        item.description.toLowerCase().includes(v) ||
        item.bodytype.toLowerCase().includes(v) ||
        item.fueltype.toLowerCase().includes(v) ||
        item.exteriorcolor.toLowerCase().includes(v) ||
        item.interiorcolor.toLowerCase().includes(v)
      );
    });
  } else {
    filteredData.value = allData.value;
  }
};

const createOrder = async (item) => {
  const data = {
    carId: item.id,
    discountamount: item.discount || 0,
    totalamount: item.price || 0,
    userid: userInfo.value.id,
    model: item.model,
    carid: item.id,
  };

  const res = await commonRequest.post("/orders/add", data);
  if (res.data.code === 200) {
    Message.success("创建成功");
    console.log("???", res.data);
    return res.data?.date;
  }
  return null;
};

const addToShoppingCart = async (item: any) => {
  const ordersid = await createOrder(item);
  if (!ordersid) {
    Message.error("订单创建失败");
  } else {
    const data = {
      ordersid,
      productid: item.id,
      userid: userInfo.value.id,
      model: item.model,
      totalamount: item.price ?? 0,
    };
    const res = await commonRequest.post("/shoppingcart/add", data);
    if (res.data.code === 200) {
      Message.success("添加成功");
    }
  }
};
// const handleReset = () => {
//   filteredData.value = allData.value;
// };

onMounted(() => {
  const userInfoJSON = localStorage.getItem("userInfo");
  userInfo.value = JSON.parse(userInfoJSON);
  getCars();
});
</script>

<style scoped>
.header {
  padding: 0 24px;
  display: flex;
  justify-content: space-between;
}

.search {
  display: flex;
  justify-content: flex-start;
  gap: 12px;
}

.car-page-wrapper {
  display: flex;
  flex-direction: column;
  gap: 24px;
}
.body {
  padding: 24px;
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  gap: 12px;
}

.time-wrapper {
  display: flex;
  justify-content: space-around;
}

.buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
